//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.baizhi.MyRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

//import edu.umd.cs.findbugs.annotations.SuppressWarnings;


public class LiangRandomRule extends AbstractLoadBalancerRule {

    //total=0,默认=0，如果=5 我们指向下一个目标
    //index=0，默认0，如果痛total=5 index+1

    private int total = 0;//被调用次数
    private int currentIndex = 0;//当前是谁在提供服务

    //@SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();//获取活着的服务
                List<Server> allList = lb.getAllServers();//从活着的服务中，随机获取一个
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
//
//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);

//                ----------------------------------------
                if(total<5){
                    server = upList.get(currentIndex);
                    total++;
                }else {
                    total = 0;
                    currentIndex++;
                    if (currentIndex>=upList.size()){
                        currentIndex = 0;
                    }
                    upList.get(currentIndex);
                }



//                --------------------------------
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }



    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
